package com.sxh.permission.service.Impl;

import com.sxh.permission.exception.BaseException;
import com.sxh.permission.map.PermissionMap;
import com.sxh.permission.model.UserRoles;
import com.sxh.permission.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class PermissionServiceImpl implements PermissionService {
    private static final Integer USER_RODE_ID=2;

    @Autowired
    private PermissionMap permissionMap;
    // 绑定默认角色（普通用户）
    @Override
    @Transactional
    public void bindDefaultRole(Long userId) {
        //查询用户是否存在？
        UserRoles userRole = new UserRoles();
        userRole.setUserId(userId);
        userRole.setRoleId(USER_RODE_ID);
        int insertResult = permissionMap.bindRole(userRole);
        if(insertResult==0){
            throw new BaseException("绑定失败");
        }
    }
    // 查询用户角色码（返回role_code）
    @Override
    @Transactional
    public String getUserRoleCode(Long userId) {
        //根据用户id查询角色码
        String roleCode = permissionMap.getUserRoleCode(userId);
        return roleCode;
    }
    // 超管调用：升级用户为管理员
    @Override
    @Transactional
    public void upgradeToAdmin(Long userId) {
        permissionMap.updateGrade(userId,"admin");
    }
    // 超管调用：降级用户为普通角色
    @Override
    @Transactional
    public void downgradeToUser(Long userId) {
        permissionMap.updateGrade(userId,"user");
    }


    //根据权限查询用户id
    //创建一个接口，传入user_roles的role_id集合，返回user_id集合
    @Override
    @Transactional
    public List<Long> queryUserIdByRoleCode(String rodeCode) {
        return permissionMap.queryUserIdByRoleCode(rodeCode);
    }
    //查询所有用户id
//    @Override
//    @Transactional
//    public List<Long> queryAllUserId(){
//        return permissionMap.queryAllUserId();
//    }
}
